from guiCommon import LeVinTreeLabel
#from profilehooks import profile


from kivyext.treegridview import MyListView
#from wineAreas import wineWorld
from levinCommon import dateFromOrdinal, wineWorld
import levinCommon
import guiCommon

tastingListWidget = None

class TastingList(MyListView):
    selectedTasting = None

    tastings = []
    doVisibilityUpdate = True
    def __init__(self, **kargs):
        kargs['hide_header'] = False
        kargs['num_columns'] = 4
        kargs['header_content'] = ['date', 'name', 'millesime', 'rate']
        kargs['columns_width_force']=[0.2,0.5,0.15,0.15]
        super(TastingList,self).__init__(**kargs)
        self.tastings = []
        def cmpDate(c1, c2):
            return cmp(c1.date, c2.date)
        self.header.sort_functions = [cmpDate] +[None]*3
        guiCommon.commonEvents.bind( on_wineselect_update = self.update_tasting_visibility)
        

    #@profile
    def populate(self):
        # Bottleneck in this function
        tastings = []
        for w in wineWorld.getWines():
            if w.tastings is None:
                continue
            for t in w.tastings:
                n = self.add_entry( tastingWidgets( t ) )
                n.tasting = t
                tastings.append(t)
        print ' Populated from ', len(wineWorld.getWines() ) , '  ',len(tastings)
        self.tastings = tastings
        
    def on__selected_node(self ,*l):
        n = l[1]
        i = self.selected_index()
        t=self.tastings[i]
        print n, n.is_visible, ' tasting vis = ', t.bottle.is_visible, n.children[1].text, t.bottle.cru_name
        
    def update_tasting_visibility(self, *l):
        if self.doVisibilityUpdate:
            for n in self._root.nodes:
                n.is_visible = n.tasting.bottle.is_visible
            

from guiTheme import ColorTheme
        
def tastingWidgets(tasting):
    b = tasting.bottle
    c = ColorTheme.green if b.color == 1 else ColorTheme.purple2

    dateW = LeVinTreeLabel(text=dateFromOrdinal(tasting.date))
    dateW.date = tasting.date # add a date attribute to wid so it can be compared
    nameW = LeVinTreeLabel(text= "[b]"+b.appellation +'[/b]  '+b.cru_name, markup = True)
    millesimeW= LeVinTreeLabel(text= str(b.millesime))
    rateW = LeVinTreeLabel(text=str(tasting.rate))
    for w in [dateW, nameW, millesimeW, rateW]:
        w.color = c
    
    return [dateW, nameW, millesimeW, rateW]
